import React, { useState } from 'react';
import 'antd/dist/antd.css';
import { Card, Input, Button, Spin, message } from 'antd';
import { UserOutlined, KeyOutlined } from '@ant-design/icons'
import { login as apiLogin } from '../api/login'

function Login(props) {
  const [userName, setUserName] = useState('')
  const [password, setPassword] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const checkLogin = () => {
    if (isLoading) return false
    if (userName === '' || password === '') {
      message.error('账号密码不能为空')
      return false
    }
    setIsLoading(true)
    let data = {
      name: userName,
      password: password
    }
    apiLogin(data)
      .then(res => {
        console.log(res)
        const { code } = res
        setIsLoading(false)
        if (code === 200) {
          props.history.push('/console/')
        } else {
          message.error('账号或密码错误')
        }
      })
      .catch(err => {
        setIsLoading(false)
        console.log(err)
        message.error('网路波动，请稍后重试')
      })
  }
  return (
    <div className="login-div">
      <Spin tip="Loading..." spinning={isLoading}>
        <Card title="老王的Blog" bordered={true} style={{ width: 400 }} >
          <Input
            id="userName"
            size="large"
            placeholder="Enter your userName"
            prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
            onChange={(e) => { setUserName(e.target.value) }}
            value={userName}
          />
          <br /><br />
          <Input.Password
            id="password"
            size="large"
            placeholder="Enter your password"
            prefix={<KeyOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
            onChange={(e) => { setPassword(e.target.value) }}
            value={password}
          />
          <br /><br />
          <Button type="primary" size="large" block onClick={checkLogin} > Login in </Button>
        </Card>
      </Spin>
      <style>{`
        .login-div{
          margin: 150px auto;
          width: 400px;
       }
        body{
            background-color: #f0f0f0;
            overflow:hidden;
        }
      `}</style>
    </div>
  )
}

export default Login